# -*- coding:utf-8 -*-
from config import *
import json


class Upload(LineReceiver):
    def __init__(self):
        self.fp = None
        self.status = None
        self.total = 0
        self.timer = MyTimer()
        self.echo = {
            "command": "upload",
            "key": KEY
        }
        # 根据命令行 查找对应的命令

    def dataReceived(self, data):
        if not self.status:
            ret = json.loads(data)
            self.echo['server_path'] = ret['server_path']
            if ret == self.echo:
                self.fp = open(ret['server_path'], "wb")
                self.status = status.LOOP
                self.sendLine(data)
            else:
                self.stopProducing()
        elif self.status == status.LOOP:
            self.total += len(data)
            self.fp.write(data)
            str = self.timer.get(os.path.getsize(self.echo['server_path']), self.total)
            if str:
                print str

    def connectionLost(self, reason):
        print my_size(self.total)+" received"
        if self.fp:
            self.fp.close()
